document.addEventListener("DOMContentLoaded", () => {
  const socket = io();
  const loginContainer = document.getElementById("login-container");
  const chatRoom = document.getElementById("chat-room");
  const usernameInput = document.getElementById("username-input");
  const loginBtn = document.getElementById("login-btn");
  const usernameError = document.getElementById("username-error");
  const messageInput = document.getElementById("message-input");
  const sendBtn = document.getElementById("send-btn");
  const messagesContainer = document.getElementById("messages");
  const userList = document.getElementById("user-list");

  let currentUsername = "";

  // 登录处理
  loginBtn.addEventListener("click", () => {
    const username = usernameInput.value.trim();
    if (username) {
      socket.emit("set username", username);
    }
  });

  // 用户名已存在
  socket.on("username exists", () => {
    usernameError.textContent = "用户名已存在，请选择其他用户名";
  });

  // 用户名设置成功
  socket.on("username set", (username) => {
    currentUsername = username;
    loginContainer.style.display = "none";
    chatRoom.style.display = "flex";
    messageInput.focus();
  });

  // 用户加入通知
  socket.on("user joined", (username) => {
    if (username !== currentUsername) {
      addNotification(`${username} 加入了聊天室`);
    }
  });

  // 用户离开通知
  socket.on("user left", (username) => {
    addNotification(`${username} 离开了聊天室`);
  });

  // 更新用户列表
  socket.on("update users", (users) => {
    userList.innerHTML = "";
    users.forEach((user) => {
      const li = document.createElement("li");
      li.textContent = user;
      if (user === currentUsername) {
        li.style.fontWeight = "bold";
        li.textContent += " (你)";
      }
      userList.appendChild(li);
    });
  });

  // 接收消息
  socket.on("chat message", (data) => {
    addMessage(data.user, data.message);
  });

  // 发送消息
  sendBtn.addEventListener("click", sendMessage);
  messageInput.addEventListener("keypress", (e) => {
    if (e.key === "Enter") {
      sendMessage();
    }
  });

  function sendMessage() {
    const message = messageInput.value.trim();
    if (message) {
      socket.emit("chat message", message);
      messageInput.value = "";
    }
  }

  function addMessage(user, message) {
    const messageElement = document.createElement("div");
    messageElement.className = "message";

    const time = new Date().toLocaleTimeString();

    messageElement.innerHTML = `
      <div class="header">
        <span class="user">${user}</span>
        <span class="time">${time}</span>
      </div>
      <div class="content">${message}</div>
    `;

    messagesContainer.appendChild(messageElement);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
  }

  function addNotification(text) {
    const notification = document.createElement("div");
    notification.className = "notification";
    notification.textContent = text;
    messagesContainer.appendChild(notification);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
  }
});
